import { Button, Form, Input, Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import React, { useState, useContext }  from 'react';
import axios from 'axios'
import AdminInfoContext from '../../context/adminInfoContext';

// 定义了叫  base64 的函数
const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};

// 定义了一个叫做   beforeUpload的函数
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

  if (!isJpgOrPng) {
    message.error('请上传 JPG/PNG 文件!');
  }

  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLt2M) {
    message.error('图片不可超过2MB!');
  }

  return isJpgOrPng && isLt2M;
};

const Setting = () => {
  const [loading, setLoading] = useState(false);  // 定义一个变量 loading  默认值是 false
  const [imageUrl, setImageUrl] = useState();  // 定义了一个变量  imageUrl
  const AdminInfo = useContext(AdminInfoContext)
  
  
  const onFinish = (values) => {
    let obj = {
      id: localStorage.getItem('adminId')
    }
    values.username && (obj.username = values.username)
    values.password && (obj.password = values.password)
    imageUrl && (obj.avatar = imageUrl)


    axios.post('/api/changeAdmin', {
      adminInfo: obj
    }).then(data =>{
      if (data.data.code === 200) {
        message.success('修改成功');
        AdminInfo.setCount(AdminInfo.count+1)

      }else{
        message.error('修改失败');
      }
    })
    
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

   // 定义了一个函数   handleChange
   const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }

    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };


  // 定义了一个变量  uploadButton   值是html
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传头像
      </div>
    </div>
  );

  return (
    <Form
      name="basic"
      labelCol={{
        span: 5,
      }}
      wrapperCol={{
        span: 16,
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="管理员名称"
        name="username"
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="密码"
        name="password"
      >
        <Input.Password />
      </Form.Item>
      <Form.Item
        label="管理员头像"
        name="avatar"
      >
          <Upload
            name="avatar"
            listType="picture-card"
            action="/api/upload"
            showUploadList={false}
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imageUrl ? (
              <img
                src={imageUrl}
                alt="avatar"
                style={{
                  width: '100%',
                }}
              />
            ) : (
              uploadButton
            )}
          </Upload>
      </Form.Item>
      

      <Form.Item
        wrapperCol={{
          offset: 5,
          span: 16,
        }}
      >
        <Button type="primary" htmlType="submit">
          确认修改
        </Button>
      </Form.Item>
      
    </Form>
  );
};

export default Setting;



